package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qujia.common.config.QuJiaConfig;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.ActiveSendCoupon;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.Grade;
import com.qujia.station.domain.vo.EnterpriseVo;
import com.qujia.station.domain.vo.StationEnterpriseCopInfo;
import com.qujia.station.mapper.EnterpriseMapper;
import com.qujia.station.mapper.StationEnterpriseCopMapper;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IGradeService;
import com.qujia.system.domain.HttpRequestUtil;
import com.qujia.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 油站信息Service业务层处理
 * 
 * @author qujia
 * @date 2020-12-08
 */
@Service
@Slf4j
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper,Enterprise> implements IEnterpriseService
{
    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IGradeService gradeService;

    @Value("${domain.payName}")
    private String domainName;

    @Autowired
    private StationEnterpriseCopMapper stationEnterpriseCopMapper;

    /**
     * 查询油企信息
     *
     * @param enterpriseId 油企信息ID
     * @return 油企信息
     */
    public Enterprise selectEnterpriseById(Long enterpriseId){
        return  enterpriseMapper.selectEnterpriseById(enterpriseId);
    }

    /**
     * 查询油企信息列表
     *
     * @param enterprise 油企信息
     * @return 油企信息集合
     */
    public List<Enterprise> selectEnterpriseList(Enterprise enterprise){
        return  enterpriseMapper.selectEnterpriseList(enterprise);
    }


    /**
     * 查询油企信息列表
     *
     * @param enterprise 油企信息
     * @return 油企信息集合
     */
    public List<Enterprise> transactionEnterpriseList(Enterprise enterprise){
        return  enterpriseMapper.transactionEnterpriseList(enterprise);
    }


    /**
     * 创建微信卡卷，并且进行参数设置
     *
     * @param enterprise 油企信息
     * @return 结果
     */
    public AjaxResult createCardEnterprise(Enterprise enterprise){

        //redisCache.deleteObject("access_token_"+enterprise.getGzhAppId());
       //判断当前的信息是正式的还是测试的网址
        String dizhi="";
        String tokeurl="";
        if("/mnt/uploadfile/images//upload".equals(QuJiaConfig.getUploadPath())){
            dizhi=domainName+"/authen";
            //dizhi="https://map.91cheyibao.com/authen";
            //tokeurl="https://test.91cheyibao.com/apipay/getAccessTokenFromSaas";
            tokeurl=domainName+"/apipay/getAccessTokenFromSaas";
        }else {
            dizhi=domainName+"/authen";
            tokeurl=domainName+"/apipay/getAccessTokenFromSaas";
        }
       // redisCache.deleteObject("access_token_"+enterprise.getGzhAppId());
        String token="";
        String tokenJson="";
        token  = redisCache.getCacheObject("access_token_"+enterprise.getGzhAppId());
        log.info("创建微信卡卷，toke授权 token:"+token+"|gzhAppId:"+enterprise.getGzhAppId());
            if("".equals(token)||token==null){
                if (Objects.isNull(enterprise.getGzhAppSecret())){
                    tokenJson = "{\n" +
                            "    \"appId\":\"" + enterprise.getGzhAppId() + "\"\n" + "}";
                            log.info("进来的是第三方请求-------------");
                }else {
                    tokenJson = "{\n" +
                            "    \"appId\":\"" + enterprise.getGzhAppId() + "\",\n" +
                            "    \"appSecret\":\"" + enterprise.getGzhAppSecret() + "\"\n" +
                            "}";
                }
                log.info("请求地址是:"+tokeurl+"---------------"+tokenJson);
            JSONObject  tokenmessage=HttpRequestUtil.getHttpsRequestData(tokeurl,"POST",tokenJson);
            Integer code =tokenmessage.getInteger("retCode");
            if(code !=0){
               return AjaxResult.error(tokenmessage.getString("message"),code);
            }
            token=tokenmessage.getString("data");
        }
        if("".equals(token)||token==null){
          return AjaxResult.error("无法获取token信息");
        }
        String url="https://api.weixin.qq.com/card/create?access_token="+token;
        String method="POST";
                     //微信创建卡卷所需要的参数，string转换之后，可能会报参数类型错误，尽量是直接从json串中复制过来
                    String mes= "{\n    \"card\": {\n        \"card_type\": \"MEMBER_CARD\",\n        \"member_card\": {\n            \"base_info\": {\n                \"logo_url\": \""+enterprise.getCardLogo()+"\",\n                \"brand_name\": \""+enterprise.getEnterpriseName()+"\",\n                \"code_type\": \"CODE_TYPE_TEXT\",\n                \"title\": \""+enterprise.getEnterpriseName()+"会员卡"+"\",\n                \"color\": \"Color010\",\n                \"notice\": \"使用时向加油员出示\",\n           \"description\": \"不定期推出各种活动\",\n                \"date_info\": {\n                    \"type\": \"DATE_TYPE_PERMANENT\"\n                },\n                \"sku\": {\n                    \"quantity\": 50000000\n                },\n                \"get_limit\": 1,\n                \"use_custom_code\": false,\n                \"can_give_friend\": true,\n                \"need_push_on_view\": true\n            },\n            \"supply_bonus\": true,\n            \"supply_balance\": false,\n            \"prerogative\": \"会员加油更优惠\",\n            \"custom_field1\": {\n                \"name\": \"我的\",\n                \"url\": \""+domainName+enterprise.getEnterpriseId()+"/my\"\n            },\n   \"activate_url\": \""+dizhi+"\",\n           \"wx_activate\": true,\n            \"wx_activate_after_submit\": true,\n            \"wx_activate_after_submit_url\": \""+dizhi+"\"\n        }\n    }\n}";
                    JSONObject message= HttpRequestUtil.getHttpsRequestData(url,method,mes);
                    log.info("message是:"+message+"-----token是--"+token);
                    if(!"0".equals(message.getString("errcode"))){
                        return AjaxResult.error(message.getString("errmsg"));
                    }
                    //微信设置卡卷参数，json串尽量不要去转化
                    String setJson="{\"card_id\":\""+message.getString("card_id")+"\",\"required_form\":{\"can_modify\":true,\"common_field_id_list\":[\"USER_FORM_INFO_FLAG_MOBILE\"]}}";
                    String seturl="https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token="+token;
                    JSONObject  setmessage= HttpRequestUtil.getHttpsRequestData(seturl,method,setJson);
                    if(!"0".equals(setmessage.getString("errcode"))){
                        return AjaxResult.error(setmessage.getString("errmsg"));
                    }
                    return AjaxResult.success(message.getString("card_id"));

    }


    /*
     * 微信公众号推送
     * @param appId
     * @param appSecret
     * @param templateId
     * @param openId
     * @param wxMpTemplateDataList
     */
    public Integer push(  String openId, Enterprise enterprise,String url,String message1, ActiveSendCoupon activeSendCoupon){

        //创建对象
        WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //公众号token缓存处理
        //String tokenCache = weiXinUserUtil.getTokenByRedisCache(appId, appSecret);
        String tokenCache ="";

        String tokeurl="";

        wxMpInMemoryConfigStorage.setAppId(enterprise.getGzhAppId());
        wxMpInMemoryConfigStorage.setSecret(enterprise.getGzhAppSecret());

        if("/mnt/uploadfile/images//upload".equals(QuJiaConfig.getUploadPath())){

            //tokeurl="https://test.91cheyibao.com/apipay/getAccessTokenFromSaas";
            tokeurl=domainName+"/apipay/getAccessTokenFromSaas";

        }else {

            tokeurl=domainName+"/apipay/getAccessTokenFromSaas";
        }
        // redisCache.deleteObject("access_token_"+enterprise.getGzhAppId());

        tokenCache  = redisCache.getCacheObject("access_token_"+enterprise.getGzhAppId());
        if("".equals(tokenCache)||tokenCache==null){

            String tokenJson="{\n" +
                    "    \"appId\":\""+enterprise.getGzhAppId()+"\",\n" +
                    "    \"appSecret\":\""+enterprise.getGzhAppSecret()+"\"\n" +
                    "}";
            JSONObject tokenmessage=HttpRequestUtil.getHttpsRequestData(tokeurl,"POST",tokenJson);
            Integer mm1=tokenmessage.getInteger("retCode");

            tokenCache=tokenmessage.getString("data");
        }
        String url1="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+tokenCache;
        String method="POST";
        String mes="    {\n" +
                "           \"touser\":\""+openId+"\",\n" +
                "           \"template_id\":\""+enterprise.getTemplateId()+"\",\n" +
                "           \"url\":\""+url+"\",  \n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":\"恭喜获得专属优惠券，请点击领取!\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword1\":{\n" +
                "                       \"value\":\""+"点击领取优惠券"+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword2\":{\n" +
                "                       \"value\":\""+sdf.format(date)+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":\""+activeSendCoupon.getMessage().replace("\n","\\n")+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   }\n" +
                "           }\n" +
                "       }";


        JSONObject message= HttpRequestUtil.getHttpsRequestData(url1,method,mes);
        if(!"0".equals(message.getString("errcode"))){
            return 0;
        }else {
            return 1;
        }


    }
    /**
     * 修改微信卡卷id
     *
     * @param enterprise 油企信息
     * @return 结果
     */
    @CacheEvict(value = { "EnterpriseServiceImpl_selectStaInfoList"},
            key="'e_' + #root.args[0].getEnterpriseId()",
            condition = "#root.args[0] != null"
    )
    public AjaxResult updateCardEnterprise(Enterprise enterprise){

        //redisCache.deleteObject("access_token_"+enterprise.getGzhAppId());
        //判断当前的信息是正式的还是测试的网址
        String dizhi="";
        String tokeurl="";
        String  mm=QuJiaConfig.getUploadPath();
        if("/mnt/uploadfile/images//upload".equals(QuJiaConfig.getUploadPath())){

            //tokeurl="https://test.91cheyibao.com/apipay/getAccessTokenFromSaas";
            tokeurl=domainName+"/apipay/getAccessTokenFromSaas";
        }else {

            tokeurl=domainName+"/apipay/getAccessTokenFromSaas";
        }
        // redisCache.deleteObject("access_token_"+enterprise.getGzhAppId());
        String token="";
        token  = redisCache.getCacheObject("access_token_"+enterprise.getGzhAppId());
        if(token == null || token.isEmpty()){
            String appSecret = enterprise.getGzhAppSecret();
            String tokenJson = "";
            if (appSecret == null) {
                tokenJson = "{\n" +
                        "    \"appId\":\"" + enterprise.getGzhAppId() + "\",\n" +
                        "    \"appSecret\":" + appSecret + "\n" +
                        "}";
            }else{
                tokenJson="{\n" +
                        "    \"appId\":\""+enterprise.getGzhAppId()+"\",\n" +
                        "    \"appSecret\":\""+enterprise.getGzhAppSecret()+"\"\n" +
                        "}";
            }
            JSONObject  tokenmessage=HttpRequestUtil.getHttpsRequestData(tokeurl,"POST",tokenJson);
            Integer mm1=tokenmessage.getInteger("retCode");
            if(tokenmessage.getInteger("retCode")!=0){
                return  AjaxResult.error("请求获取token失败");
            }
            token=tokenmessage.getString("data");
        }
        if(token == null || token.isEmpty()){
            return AjaxResult.error("无法获取token信息");
        }

        String method="POST";
        //微信创建卡卷所需要的参数，string转换之后，可能会报参数类型错误，尽量是直接从json串中复制过来

        //微信设置卡卷参数，json串尽量不要去转化

        String setJSon="{\n" +
                "    \"card_id\": \""+enterprise.getCardId()+"\",\n" +
                "    \"member_card\": {\n" +
                "        \"custom_field1\": {\n" +
                "            \"name\": \"我的\",\n" +
                "            \"url\": \""+domainName+enterprise.getEnterpriseId()+"/my\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        String seturl="https://api.weixin.qq.com/card/update?access_token="+token;
        JSONObject  setmessage=HttpRequestUtil.getHttpsRequestData(seturl,method,setJSon);
        if(!"0".equals(setmessage.getString("errcode"))){
            return AjaxResult.error("设置参数失败");
        }
        return AjaxResult.success("成功");

    }

    /**
     * 新增油企信息
     *
     * @param enterprise 油企信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertEnterprise(Enterprise enterprise) throws Exception{
       int i=   enterpriseMapper.insertEnterprise(enterprise);
       if(i>0&&enterprise.getGzhAppId()!=null&&!"".equals(enterprise.getGzhAppId())){
           Enterprise enterprise1=enterpriseMapper.selectEnterpriseList(enterprise).get(0);
          if( !"200".equals(updateCardEnterprise(enterprise1).get("code")+"")){
              throw  new SQLException();
          }
       }
      return i;
    }

    /**
     * 第三方新增油企
     *
     * @param
     * @return 结果
     */
    @Transactional
    public AjaxResult addEnterprise(EnterpriseVo enterpriseVo) throws Exception{
        //查询是否存在
        String copId = enterpriseVo.getCopId();
        StationEnterpriseCopInfo stationEnterpriseCopInfo = new StationEnterpriseCopInfo();
        stationEnterpriseCopInfo.setCopId(copId);
        stationEnterpriseCopInfo.setType(1);

        StationEnterpriseCopInfo copIdRes = stationEnterpriseCopMapper.selectByCopId(stationEnterpriseCopInfo);
        if(Objects.nonNull(copIdRes)){
          //如果存在就修改
            Enterprise enterprise = enterpriseMapper.selectEnterpriseById(copIdRes.getEnterpriseId());
            Enterprise enterpriseTemp = new Enterprise();
            enterpriseTemp.setEnterpriseName(enterpriseVo.getEnterpriseName());
            enterpriseTemp.setEnterpriseId(enterprise.getEnterpriseId());
            Enterprise enterpriseRes = enterpriseMapper.selectEnterpriseById(enterprise.getEnterpriseId());
            enterpriseMapper.updateEnterprise(enterpriseTemp);

            return AjaxResult.success("更新油企成功", enterpriseRes.getEnterpeiseCode());
        }


        Calendar cal = Calendar.getInstance();
        Random random=new Random();
        String result1 = "";
        for (int m = 0; m < 4; m++) {
            result1 += random.nextInt(10);
        }
        int year = cal .get(Calendar.YEAR);
        int month = cal .get(Calendar.MONTH) + 1;
        int yearcount=year-2000;
        String code="C"+yearcount+month+"0001"+result1;

        Enterprise enterprise = new Enterprise();
        enterprise.setEnterpriseName(enterpriseVo.getEnterpriseName());
        enterprise.setEnterpeiseCode(code);
        enterprise.setStatus(enterpriseVo.getStatus());
        Long i = enterpriseMapper.insertEnterpriseAndGetKey(enterprise);
        if(i<=0){
            return AjaxResult.error("新增失败");
        }

        stationEnterpriseCopInfo.setEnterpriseId(enterprise.getEnterpriseId());
        Integer res = stationEnterpriseCopMapper.insertInfo(stationEnterpriseCopInfo);
        if(res<=0){
            return AjaxResult.error("新增失败");
        }

        String [] codevalue={"1","2","3","4","5"};
        String [] name={"普卡","白银","黄金","钻石","黑卡"};
        Long [] growvalue={0L, 900000000L,900000001L,900000002L,900000003L};
        Long[] roles={Long.parseLong(18+"")};

        Enterprise enterprise1 = selectEnterpriseList(enterprise).get(0);
        SysUser sysUser=new SysUser();
        sysUser.setDeptId((long) 100);
        sysUser.setUserName(code);
        sysUser.setNickName(enterprise.getEnterpriseName());
        sysUser.setUserLevel("1");
        sysUser.setPhonenumber(enterprise.getPhone());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setEnterpriseId(enterprise1.getEnterpriseId());
        sysUser.setRoleIds(roles);
        int insertUserRes =sysUserService.insertUser(sysUser);
        if(insertUserRes<=0){
            throw new  SQLException("插入用户失败");
        }
        for(int m=0;m<5;m++){
            Grade grade=new Grade();
            grade.setEnterpriseId(enterprise1.getEnterpriseId());
            grade.setGradeGrowValue(growvalue[m]);

            grade.setCreateTime(new Date());
            grade.setGradeName(name[m]);
            grade.setGradeCode(codevalue[m]);
            gradeService.insertGrade(grade);
        }

        return AjaxResult.success("新增油企成功",code);
    }


    /**
     * 修改油企信息
     *
     * @param enterprise 油企信息
     * @return 结果
     */
    @CacheEvict(value = { "EnterpriseServiceImpl_selectStaInfoList"},
            key="'e_' + #root.args[0].getEnterpriseId()",
            condition = "#root.args[0] != null"
    )
    @Transactional(rollbackFor = Exception.class)
    public int updateEnterprise(Enterprise enterprise) throws Exception{
        enterprise.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(enterprise.getCardUseRangeFlag())) {
            Enterprise old = enterpriseMapper.selectEnterpriseById(enterprise.getEnterpriseId());
            if (StringUtils.isNotBlank(old.getCardUseRangeFlag())
                    && !StringUtils.equals(old.getCardUseRangeFlag(),enterprise.getCardUseRangeFlag())) {
                throw new CustomException("电子卡使用范围不可修改");
            }
        }
        int i=   enterpriseMapper.updateEnterprise(enterprise);
        if(i>0&&enterprise.getGzhAppId()!=null&&!"".equals(enterprise.getGzhAppId())&&enterprise.getCardId()!=null){
            if( !"200".equals(updateCardEnterprise(enterprise).get("code")+"")){
                throw  new SQLException(updateCardEnterprise(enterprise).get("msg")+"");
            }
        }
        return i;
    }

    /**
     * 删除油企信息
     *
     * @param enterpriseId 油企信息ID
     * @return 结果
     */
    public int deleteEnterpriseById(Long enterpriseId){
        return  enterpriseMapper.deleteEnterpriseById(enterpriseId);
    }

    /**
     * 批量删除油企信息
     *
     * @param enterpriseIds 需要删除的数据ID
     * @return 结果
     */
    public int deleteEnterpriseByIds(Long[] enterpriseIds){
        return  enterpriseMapper.deleteEnterpriseByIds(enterpriseIds);
    }

    @Override
    public Enterprise selectEnterpriseByStationId(Long stationId) {
        return enterpriseMapper.selectEnterpriseByStationId(stationId);
    }

    @Override
    public int initgzhFunction(Long enterpriseId) {
        return enterpriseMapper.initgzhFunction(enterpriseId);
    }

    @Override
    public int updateEnterpriseCardLogo(Enterprise enterprise) {
        return enterpriseMapper.updateEnterprise(enterprise);
    }

    @Override
    public List<Enterprise> selectEnterpriseByIds(Long[] enterpriseIds) {
        return enterpriseMapper.selectEnterpriseByIds(enterpriseIds);
    }
}
